#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"

using namespace std;
using task_t = function<void()>;

class MessageRoute
{
private:
    bool IsExist(const InetAddr &addr)
    {
        for(auto& a : _onlineuser)
        {
            if(a == addr)
            {
                return true;
            }
        }
        return false;
    }
public:
    MessageRoute() 
    {
        pthread_mutex_init(&_mutex, nullptr);
    }

    void AddUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        if(IsExist(addr))
        {
            return;
        }
        _onlineuser.push_back(addr);
    }

    void DelUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        for(auto iter=_onlineuser.begin(); iter<_onlineuser.end(); iter++)
        {
            if(*iter == addr)
            {
                _onlineuser.erase(iter);// 删除指向的位置
                break;
            }
        }
    }

    void RouteHelper(int sockfd, string message, InetAddr addr)
    {
        LockGuard lockguard(&_mutex);
        // 消息转发
        for(auto u : _onlineuser)
        {
            string send_message = "[" + addr.Ip() + ":" + to_string(addr.Port()) + "]# " + message + "\n";

            struct sockaddr_in clientaddr = u.getAddr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr*)&clientaddr, sizeof(clientaddr));
        }
    }

    void Route(int sockfd, string message, InetAddr addr)
    {
        // 增加在线用户
        AddUser(addr);

        // 删除用户——退出
        if(message == "q" || message == "quit")
        {
            DelUser(addr);
        }

        task_t t = bind(&MessageRoute::RouteHelper, this, sockfd, message, addr);
        ThreadPool<task_t> *tp = new ThreadPool<task_t>();
        tp->InitThreadPool();
        tp->Start();
        tp->Enqueue(t);
    }

    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }
private:  
    vector<InetAddr> _onlineuser;
    pthread_mutex_t _mutex;
};